package com.itheima.bigevent2.controller;

import com.itheima.bigevent2.pojo.Result;
import com.itheima.bigevent2.pojo.User;
import com.itheima.bigevent2.service.UserService;
import com.itheima.bigevent2.utils.JwtUtil;
import com.itheima.bigevent2.utils.Md5Util;
import jakarta.validation.constraints.Null;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    //因为注册的请求是post
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$")  String password)
    {
        //查询用户
        User u=userService.findByUserName(username);
        if(u==null)
        {
            //说明没有被占用
            userService.register(username,password);
            //注册
            return Result.success();
        }
        else
        {
            //被占用了
            return Result.error("用户名已经被占用");
        }

    }
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$")  String password)
    {
        //根据用户名查询用户
        User loginUser=userService.findByUserName(username);
        if(loginUser==null)
        {   //未查询到用户
            return Result.error("用户名错误");
        }
       if(Md5Util.getMD5String(password).equals(loginUser.getPassword()))
       {
           //登录成功
           Map<String,Object> claims=new HashMap<>();
           claims.put("id",loginUser.getId());
           claims.put("username",loginUser.getUsername());
           String token= JwtUtil.genToken(claims);
           return Result.success(token);
       }
       return Result.error("密码错误");
    }


}
